<?php
define('MYSQL_CONFIG', CONFIG_PATH . 'mysql.ini');

class db {
	var $ready = false;
	var $last_error = '';
	
	var $connection;
	var $config = array();
	
	var $queries = array();
	var $results = array();
	var $last_query_num = -1;
	
	function db(){
		if(!($this->config = @parse_ini_file(MYSQL_CONFIG))){
			show_error('Cannot load mysql configuration');
		}
		
		if(!extension_loaded('mysql')){
			show_error('Unable to load module for database server "mysql": PHP mysql extension not available!');
			return false;
		}
		
		if($this->config['persistent']){
			$this->connection = @mysql_pconnect($this->config['server'], $this->config['username'], $this->config['password']);
		} else {
			$this->connection = @mysql_connect($this->config['server'], $this->config['username'], $this->config['password']);
		}
		
		if(empty($this->connection) || !@mysql_select_db($this->config['database'], $this->connection)){
			$this->error(mysql_error());
			return false;
		}
				
		$this->ready = true;
		return true;
	}
	
	function error($text, $query = ''){
		$this->last_error = $text;
		show_window('MySQL Error', $text . ((!empty($query)) ? '<hr />' . $query : ''));
	}
	
	function query($query) {
		$this->queries[] = preg_replace('#\s+#', ' ', $query);
		$result = @mysql_query($query, $this->connection) or $this->error(mysql_error(), $query);
		if (is_resource($result)){
			$this->results[] = $result;
		}
		$this->last_query_num++;
		return $result;
		
	}
	
	function fetch_result($result = -1) {
		if(is_resource($result)){
			return @mysql_fetch_array($result, MYSQL_ASSOC);
		} elseif($result === -1){
			return @mysql_fetch_array($this->results[$this->last_query_num], MYSQL_ASSOC);
		} elseif(!empty($this->results[$result])) {
			return @mysql_fetch_array($this->results[$result], MYSQL_ASSOC);
		} else {
			return false;
		}
	}
	
	function num_rows($result = -1) {
		if(is_resource($result)){
			return @mysql_num_rows($result);
		} elseif($result === -1){
			return @mysql_num_rows($this->results[$this->last_query_num]);
		} elseif(!empty($this->results[$result])) {
			return @mysql_num_rows($this->results[$result]);
		} else {
			return false;
		}
	}
	
	function last_id() {
		return mysql_insert_id($this->connection);
	}
	
	function get_used_queries() {
		return $this->queries;
	}
	
	function disconnect() {
		@mysql_close($this->connection);
	}
}

?>
